package com.atguigu.eduservice.controller;


import com.atguigu.commonutils.R;
import com.atguigu.eduservice.entity.EduTeacher;
import com.atguigu.eduservice.entity.vo.TeacherQuery;
import com.atguigu.eduservice.service.EduTeacherService;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * <p>
 * 讲师 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2021-08-11
 */
@Api(description = "讲师管理")
@RestController
@RequestMapping("/eduservice/teacher")
@CrossOrigin   //解决跨域问题
public class EduTeacherController {

    //把service注入进来
    @Autowired
    private EduTeacherService teacherService;


    //1.查询讲师表的所有数据
    //访问地址：http://localhost:8080//eduservice/teacher/findAll
    @ApiOperation(value = "所有讲师列表")   //swagger里的解释说明。
    @GetMapping("/findAll")    //rest风格
    //private List<EduTeacher> findAllteacher(){
    public R findAllteacher(){   //将返回值类型改为:统一返回结果类型R。
        List<EduTeacher> list = teacherService.list(null);  //调用service的方法查询所有teacher。
        return R.ok().data("items",list);  //链式调用，并以key，value的形式返回数据。
    }


    //2.逻辑删除讲师的方法
    @ApiOperation(value = "根据ID逻辑删除讲师")   //swagger里的解释说明。
    @DeleteMapping("{id}")     //id值需要通过路径进行传递
    //public boolean removeTeacher(@ApiParam(name = "id", value = "讲师ID", required = true) @PathVariable String id){  //@ApiParam(name = "id", value = "讲师ID", required = true) 是swagger里的解释说明,required = true表示必填。
    public R removeTeacher(@ApiParam(name = "id", value = "讲师ID", required = true) @PathVariable String id){  //@ApiParam(name = "id", value = "讲师ID", required = true) 是swagger里的解释说明,required = true表示必填
        boolean flag = teacherService.removeById(id);
        if (flag) {
            return R.ok();
        }else {
            return R.error();
        }
    }


    //3.分页查询讲师的方法
    @GetMapping("pageTeacher/{current}/{limit}")
    public R pageListTeacher(@PathVariable long current,
                             @PathVariable long limit){   //current：当前页、limit：每页记录数
        //创建page对象
        Page<EduTeacher> pageTeacher = new Page<EduTeacher>(current, limit);

        try {
            int i = 10/0;   //统一异常处理测试！！！
        }catch (Exception e){
            //执行自定义异常
            throw new GuliException(20001,"执行了自定义异常处理...");
        }

        //调用方法实现分页，调用方法的时候，底层进行封装，会把分页所有数据封装到pageTeacher对象里面
        teacherService.page(pageTeacher,null);

        long total = pageTeacher.getTotal();   //总记录数
        List<EduTeacher> records = pageTeacher.getRecords();   //返回的数据，存放在list集合中

        return R.ok().data("total",total).data("rows",records);  //将total和records返回。

        //上面的return方式也可以替换成下面这样：
//        Map map = new HashMap();
//        map.put("total",total);
//        map.put("rows",records);
//        return R.ok().data(map);

    }


    //4.条件查询带分页的方法
    @PostMapping("pageTeacherCondition/{current}/{limit}")
    public R pageTeacherCondition(@PathVariable long current, @PathVariable long limit,
                                  @RequestBody(required = false) TeacherQuery teacherQuery){
        //①创建page对象
        Page<EduTeacher> pageTeacher = new Page<EduTeacher>(current,limit);

        //②构建条件，多条件组合查询（mybatis学过动态sql，很类似）
        QueryWrapper<EduTeacher> wrapper = new QueryWrapper<EduTeacher>();
        //先取出name、level、begin、end然后再做判断
        String name = teacherQuery.getName();
        Integer level = teacherQuery.getLevel();
        String begin = teacherQuery.getBegin();
        String end = teacherQuery.getEnd();
        //判断下面四个条件值是否为空，如果不为空则拼接该条件
        if(!StringUtils.isEmpty(name)){
            //构建模糊查询的条件
            wrapper.like("name",name);    //like：模糊查询
        }
        if(!StringUtils.isEmpty(level)){
            wrapper.eq("level",level);    //eq：等于
        }
        if(!StringUtils.isEmpty(begin)){   //gmt_create为表中的字段名称，begin为TeacherQuery类中的属性值
            wrapper.ge("gmt_create",begin);   //大于等于
        }
        if(!StringUtils.isEmpty(end)){
            wrapper.le("gmt_modified",end);   //小于等于
        }

        //根据时间降序排序(新加的数据显示在第一个)
        wrapper.orderByDesc("gmt_create");

        //③调用方法实现条件查询分页
        teacherService.page(pageTeacher,wrapper);
        long total = pageTeacher.getTotal();   //总记录数
        List<EduTeacher> records = pageTeacher.getRecords();   //返回的数据，存放在list集合中
        return R.ok().data("total",total).data("rows",records);
    }


    //5.添加讲师功能
    @ApiOperation(value = "新增讲师")
    @PostMapping("addTeacher")
    public R addTeacher(@RequestBody EduTeacher eduTeacher){    //@RequestBody用json传输，用RequestBody接收。
        boolean save = teacherService.save(eduTeacher);
        if(save){
            return R.ok();
        }else{
            return R.error();
        }
    }


    //6.修改讲师功能（先根据讲师id进行查询，然后再修改）

    //根据讲师id进行查询
    @GetMapping("getTeacher/{id}")
    public R getTeacher(@PathVariable String id){
        EduTeacher eduTeacher = teacherService.getById(id);
        return R.ok().data("teacher",eduTeacher);
    }

    //进行修改
    @PostMapping("updateTeacher")
    public R updateTeacher(@RequestBody EduTeacher eduTeacher){
        boolean flag = teacherService.updateById(eduTeacher);
        if (flag){
            return R.ok();
        }else {
            return R.error();
        }

    }

}









